package tool

import (
	"context"
	"fmt"
	"openmanus/llm"
	"strings"

	logger "github.com/axcom/ninego/log"
	mcpclient "github.com/mark3labs/mcp-go/client"
	"github.com/mark3labs/mcp-go/mcp"
)

type MCPClientTool struct {
	ToolBase

	mcpClient *mcpclient.Client
}

func NewMCPClientTool(name, description string, parameters llm.Schema, client *mcpclient.Client) *MCPClientTool {
	return &MCPClientTool{ToolBase: *NewToolBase(name, description, parameters), mcpClient: client}
}

// Execute 执行MCP工具
func (t *MCPClientTool) Execute(toolArgs map[string]interface{}) (*ToolResult, error) {
	parts := strings.Split(t.Name(), "__")
	toolName := parts[1]
	var err error
	var toolResultPtr *mcp.CallToolResult

	logger.Infof("Running MCP tool %s(%+v)...\n", toolName, toolArgs)
	req := mcp.CallToolRequest{}
	req.Params.Name = toolName
	req.Params.Arguments = toolArgs
	logger.Debug("CallTool:", req)
	toolResultPtr, err = t.mcpClient.CallTool(context.Background(), req)
	logger.Debug("toolResultPtr:", toolResultPtr)

	if err != nil {
		errMsg := fmt.Sprintf(
			"Error calling tool %s: %v",
			toolName,
			err,
		)
		fmt.Printf("\n%s\n", errMsg)
		return &ToolResult{Error: errMsg}, err
	}

	toolResult := *toolResultPtr

	if toolResult.Content != nil {
		logger.Debug("raw tool result content", "content", toolResult.Content)

		// Extract text content
		var resultText string
		// Handle array content directly since we know it's []interface{}
		for _, item := range toolResult.Content {
			/*(if contentMap, ok := item.(map[string]interface{}); ok {
				if text, ok := contentMap["text"]; ok {
					fmt.Print("contentMap", text)
					resultText += fmt.Sprintf("%v ", text)
				}
			}*/
			if contentMcp, ok := item.(mcp.TextContent); ok {
				logger.Debug("contentMap", contentMcp.Text)
				resultText += fmt.Sprintf("%v ", contentMcp.Text)
			}

		}

		return &ToolResult{Output: toolResult.Content, Text: strings.TrimSpace(resultText)}, nil
	}
	return &ToolResult{Text: ""}, nil
}
